package campeonatofutebol.conn.facebook;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import campeonatofutebol.util.CarregadorDeStatus;

import com.example.campeonatofutebol.R;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;

public class CompartilharNoticiaActivity extends Activity{

	private UiLifecycleHelper uiHelper;
	private GraphUser user;
	private PendingAction pendingAction = PendingAction.NONE;
	private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
	private String messageToShare = CarregadorDeStatus.getInstance().getNovoStatus();
	private final String PENDING_ACTION_BUNDLE_KEY = "campeonatofutebol.conn.facebook:PendingAction";
	
	private enum PendingAction {
		NONE,
		POST_STATUS_UPDATE
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};


	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			PackageInfo info = getPackageManager().getPackageInfo(
					"com.example.campeonatofutebol", 
					PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {

		} catch (NoSuchAlgorithmException e) {

		}
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
			pendingAction = PendingAction.valueOf(name);
		}


		signInWithFacebook();

	};

	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
		Log.w("Compartilhar", "entrou em onResume() " + "PENDING_ACTION_BUNDLE_KEY: " + PENDING_ACTION_BUNDLE_KEY +
				"pendingAction: " + pendingAction.name());
		outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}


	private interface GraphObjectWithId extends GraphObject {
		String getId();
	}

	private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
		String title = null;
		String alertMessage = null;
		if (error == null) {
			title = getString(R.string.success);
			alertMessage = getString(R.string.successfully_posted_post, message);
		} else {
			title = getString(R.string.error);
			alertMessage = error.getErrorMessage();
		}

		new AlertDialog.Builder(this)
		.setTitle(title)
		.setMessage(alertMessage)
		.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				CompartilharNoticiaActivity.this.onBackPressed();
				
			}
		})
		.show();
	}


	@SuppressWarnings("incomplete-switch")
	private void handlePendingAction() {
		PendingAction previouslyPendingAction = pendingAction;
		// These actions may re-set pendingAction if they are still pending, but we assume they
		// will succeed.
		pendingAction = PendingAction.NONE;

		switch (previouslyPendingAction) {

		case POST_STATUS_UPDATE:
			postStatusUpdate();
			break;
		}
	}

	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		Log.w("sessionState", "state : " + state.toString());

		if (pendingAction != PendingAction.NONE &&
				(exception instanceof FacebookOperationCanceledException ||
						exception instanceof FacebookAuthorizationException)) {
			new AlertDialog.Builder(CompartilharNoticiaActivity.this)
			.setTitle(R.string.cancelled)
			.setMessage(R.string.permission_not_granted)
			.setPositiveButton(R.string.ok, null)
			.show();
			pendingAction = PendingAction.NONE ;
		}
	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null && session.getPermissions().contains("publish_actions");
	}

	private void performPublish(PendingAction action) {
		Session session = Session.getActiveSession();
		if (session != null) {
			pendingAction = action;
			if (hasPublishPermission()) {
				// We can do the action right away.
				Log.w("Compartilhar", "possui permissoes");
				handlePendingAction();
			} else {
				// We need to get new permissions, then complete the action when we get called back.
				session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
			}
		}
	}

	private void postStatusUpdate() {
		if (user != null && hasPublishPermission()) {
			Request request = Request.newStatusUpdateRequest(Session.getActiveSession(), 
					getMessageToShare(), new Request.Callback() {
				@Override
				public void onCompleted(Response response) {
					Log.w("statusUpdate", "realizando publicacao");
					showPublishResult(getMessageToShare(), response.getGraphObject(), response.getError());
				}
			});
			request.executeAsync();
		} else {
			pendingAction = PendingAction.POST_STATUS_UPDATE;
		}
	}

	private void signInWithFacebook() {


		Session.openActiveSession(this, true, new Session.StatusCallback() {

			// callback when session changes state
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				if (session.isOpened()) {

					// make request to the /me API
					Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

						// callback after Graph API response with user object
						@Override
						public void onCompleted(GraphUser user, Response response) {
							if (user != null) {
								CompartilharNoticiaActivity.this.user = user;
								performPublish(PendingAction.POST_STATUS_UPDATE);

							}
						}
					});
				}
			}
		});


	}

	public String getMessageToShare() {
		return messageToShare;
	}

	public void setMessageToShare(String messageToShare) {
		this.messageToShare = messageToShare;
	}
}
